package com.myebills.ebpsfrontend.cust.controller;

import java.io.PrintWriter;
import java.io.IOException;
import java.net.*;
import com.checkfree.isolutions.persist.*;
import com.checkfree.isolutions.customer.persist.User;
import com.checkfree.isolutions.customer.persist.UserHomeImpl;
import com.checkfree.isolutions.utility.CFiError;
import com.checkfree.isolutions.property.Properties;
import com.checkfree.isolutions.property.PropertiesConfig;
import com.ibm.logging.ILogger;
import com.ibm.logging.IRecordType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.checkfree.isolutions.security.Cipher; // the library

/**
 * This servlet simulates the EBD link to EBPS
 */
public class EbdSimulationServlet extends EbppxServlet {

    private static String hardKey="X2q3j5k6E7r8l93tm2n7H5qp";
    //private static String algo="3DES/PCBC/PKCS5";

    protected final void doRequest(
    HttpServletRequest req,
    HttpServletResponse res
    ) throws ServletException, java.io.IOException {

        ILogger trcLogger = getTraceLogger(req);
        final String fName = "doRequest";
		EbppxTransformer transform = new EbppxTransformer();

        try {
            PersistServer.activate("Maxis");
            PersistServer.beginTransaction();

            String strUserId = EbppxUtil.nullToEmpty(req.getParameter("userId"));
            String strEmail = EbppxUtil.nullToEmpty(req.getParameter("email"));
            String strAccounts = EbppxUtil.nullToEmpty(req.getParameter("accounts"));

            if (trcLogger.isLogging())
                trcLogger.entry(IRecordType.TYPE_INFO, this, fName);

            String param = strUserId + "," + strEmail + "," + strAccounts;
            //String currTimestamp = EbppxUtil.getCurrentTimestamp();
            //String myKey = currTimestamp + hardKey;

			//String param = "userId=" + strUserId + "&email=" + strEmail+ "&accounts=" + strAccounts;

			String encryptedParam = EncryptionHelper.encrypt(param,hardKey);

			System.out.println("Encrypted : " + encryptedParam);

			System.out.println("Decrypted : " + EncryptionHelper.decrypt(encryptedParam,hardKey));


            if (trcLogger.isLogging()) {
                trcLogger.text(IRecordType.TYPE_INFO, this, fName,"parameter="+param);
                //trcLogger.text(IRecordType.TYPE_INFO, this, fName,"key="+myKey);
            }

			com.checkfree.isolutions.property.Properties appCfg = com.checkfree.isolutions.property.PropertiesConfig.getApplicationSettings();

			boolean ecsEncryptionOn = false;

			if (appCfg.hasProperty("EcsEncryption") == false)
				ecsEncryptionOn = false;
			else {
				String temp = appCfg.getProperty("EcsEncryption");
				if (temp.compareToIgnoreCase("Yes")==0){
					ecsEncryptionOn = true;
				}
			}

            String encParam = new String();
            if (ecsEncryptionOn) {
				//encParam = transform.encrypt(param, currTimestamp, hardKey);
            	//encParam = Cipher.encryptFromString(algo, myKey, param, 0); //    the function to encrypt
			} else {
				encParam = param;
			}

            if (trcLogger.isLogging())
                trcLogger.text(IRecordType.TYPE_INFO, this, fName,"encrypted parameter="+encParam);

            String EBPSHOST = "";
            String EBPSPATH = "";

            EBPSHOST = appCfg.getProperty("CusAppHost");
            EBPSPATH = appCfg.getProperty("CusAppPath");
            System.out.println("Host : "+EBPSHOST);
            System.out.println("Path : "+EBPSPATH);

            //Create the link to EBPS for test purpose
            PrintWriter out = res.getWriter();
            String url = "http://"+EBPSHOST+"/"+EBPSPATH+"/EBDLogon?param="+URLEncoder.encode(encryptedParam);
            out.write("<a href='#' onclick='win_child=window.open(\""+ url +"\",\"Lendy\",\"width=800,height=480,resizable=yes,toolbar=no,status=yes,scrollbars=yes,location=no,menubar=no,directories=no\");win_child.focus();'/>");
            out.write(" Maxis Electronic Bill Presentment </a> ");

            String url2 = "http://"+EBPSHOST+"/cc/Main/ValidateLogon.jsp?companyNameIn=Maxis&logonIdIn=Lendy&passwordIn=password&newPassword=&confirmNewPw=&accNo=1.1283021";
            out.write("<br><a href='#' onclick='win_child=window.open(\""+ url2 +"\",\"Lendy\",\"width=800,height=535,resizable=yes,toolbar=no,status=yes,scrollbars=yes,location=no,menubar=no,directories=no\");win_child.focus();'/>");
            out.write(" from Clarify System </a> ");

            out.flush();
            out.close();


            if (trcLogger.isLogging())
                trcLogger.exit(IRecordType.TYPE_INFO, this, fName);

            // Close the connection to the database.
            PersistServer.commitTransaction();
        }
        catch (CFiError cfie) {
            if (trcLogger.isLogging()) {
                trcLogger.text(IRecordType.TYPE_ERROR, this, fName,"encryption error="+cfie);
            }
            // Ensure that rollback is called even when an exception occurs.
            try {
                // Ensure that rollback is called even when an exception occurs.
                PersistServer.rollbackTransaction();
            }
            catch (CFiError cfie1) {
                trcLogger.text(IRecordType.TYPE_ERROR, this, fName,"encryption error="+cfie1);
            }
        }
        finally {
            PersistServer.deactivate();
        }

    }
}
